﻿using Red.Controls.Shell;
using Red.Controls.ViewModels;
using Red.EngineData.View;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Red.Controls
{
    /// <summary>
    /// Interaction logic for AnimationSelector.xaml
    /// </summary>
    public partial class AnimationSelector : UserControl
    {
        private DataView _rootView;

        /// <summary>
        /// Called when user choose animation by mouse double click.
        /// First argument is animation set data view.
        /// Second argument is selected animation.
        /// </summary>
        public event Action<string> OnChooseEvent;

        /// <summary>
        /// Constructs.
        /// </summary>
        public AnimationSelector()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Initializes.
        /// </summary>
        public void Initialize( DataView rootView )
        {
            _rootView = rootView;

            new AnimationSetListRoot( rootView,
                item =>
                {
                    _animationList.ItemsSource = item.Children;
                    item.IsExpanded = true;
                } );
        }

        /// <summary>
        /// Execute "select()" when selection changed.
        /// </summary>
        private void AnimationList_SelectedItemChanged( object sender, RoutedPropertyChangedEventArgs<object> e )
        {
            AnimationSetEntryListItem selected = e.NewValue as AnimationSetEntryListItem;
            if ( selected != null )  // if null, then it's not an AnimationSetEntryListItem, so we want to ignore it
                selected.Select();
        }

        /// <summary>
        /// Choose animation.
        /// </summary>
        private void AnimationList_MouseDoubleClick( object sender, MouseButtonEventArgs e )
        {
            _rootView.Execute( Interop.Make( "selected.name" ),
                result =>
                {
                    if ( OnChooseEvent != null )
                    {
                        OnChooseEvent( result.Data );
                    }
                },
                ex =>
                {
                    RedMessageBox.ShowAsync( this, RedDialogType.Ok, ex.Message, "Selection error" );
                } );
        }
    }
}
